<!DOCTYPE HTML>
<html lang="zh-CN">


<head><meta name="generator" content="Hexo 3.9.0">
    <meta charset="utf-8">
    <meta name="keywords" content="zookeeper教程, java,node,Spring,大数据,javascript">
    <meta name="description" content="
zookeeper 是一个开源的分布式协调服务，由知名互联网公司雅虎公司创建，是Google Chubby 开源实现。 他致力于提供一个高性能，高可用，且具有严格的顺序访问控制能力的分布式协调服务。分布式应用可以基于诸如数据发布/订阅、负">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <title>zookeeper教程 | 码匠先生</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">
    <style type="text/css">
        
    </style>

    <script src="/libs/jquery/jquery-2.2.0.min.js"></script>
<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css"></head>


<body>

<header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">码匠先生</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fa fa-navicon"></i></a>
<ul class="right">
    
    <li class="hide-on-med-and-down">
        <a href="/" class="waves-effect waves-light">
            
            <i class="fa fa-home"></i>
            
            <span>首页</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/tags" class="waves-effect waves-light">
            
            <i class="fa fa-tags"></i>
            
            <span>标签</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/categories" class="waves-effect waves-light">
            
            <i class="fa fa-bookmark"></i>
            
            <span>分类</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/archives" class="waves-effect waves-light">
            
            <i class="fa fa-archive"></i>
            
            <span>归档</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/about" class="waves-effect waves-light">
            
            <i class="fa fa-user-circle-o"></i>
            
            <span>关于</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/friends" class="waves-effect waves-light">
            
            <i class="fa fa-address-book"></i>
            
            <span>移步大佬</span>
        </a>
    </li>
    
    <li>
        <a href="#searchModal" class="modal-trigger waves-effect waves-light">
            <i id="searchIcon" class="fa fa-search" title="搜索"></i>
        </a>
    </li>
</ul>

<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">码匠先生</div>
        <div class="logo-desc">
            
            人生百态，码于心中。
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li>
            <a href="/" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-home"></i>
                
                首页
            </a>
        </li>
        
        <li>
            <a href="/tags" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-tags"></i>
                
                标签
            </a>
        </li>
        
        <li>
            <a href="/categories" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-bookmark"></i>
                
                分类
            </a>
        </li>
        
        <li>
            <a href="/archives" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-archive"></i>
                
                归档
            </a>
        </li>
        
        <li>
            <a href="/about" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-user-circle-o"></i>
                
                关于
            </a>
        </li>
        
        <li>
            <a href="/friends" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-address-book"></i>
                
                友情链接
            </a>
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/liushaojun/liushaojun.github.io" class="waves-effect waves-light" target="_blank">
                <i class="fa fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>

        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/liushaojun/liushaojun.github.io" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>


<script src="/libs/cryptojs/crypto-js.min.js"></script>
<script>
    (function() {
        let pwd = '';
        if (pwd && pwd.length > 0) {
            if (pwd !== CryptoJS.SHA256(prompt('请输入访问本文章的密码')).toString(CryptoJS.enc.Hex)) {
                alert('密码错误，将返回主页！');
                location.href = '/';
            }
        }
    })();
</script>




<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/14.jpg')">
    <div class="container">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <div class="description center-align post-title">
                        zookeeper教程
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>



<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #toc-content .is-active-link::before {
        background-color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 20px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/zookeeper/" target="_blank">
                                <span class="chip bg-color">zookeeper</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fa fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/Java/" class="post-category" target="_blank">
                                Java
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                <div class="post-date info-break-policy">
                    <i class="fa fa-calendar-minus-o fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2016-07-27
                </div>

                
                    
                    <div class="info-break-policy">
                        <i class="fa fa-file-word-o fa-fw"></i>文章字数:&nbsp;&nbsp;
                        3.3k
                    </div>
                    

                    
                    <div class="info-break-policy">
                        <i class="fa fa-clock-o fa-fw"></i>阅读时长:&nbsp;&nbsp;
                        18 分
                    </div>
                    
                
				
				
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="fa fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <blockquote>
<p>zookeeper 是一个开源的分布式协调服务，由知名互联网公司雅虎公司创建，是Google Chubby 开源实现。 他致力于提供一个高性能，高可用，且具有严格的顺序访问控制能力的分布式协调服务。分布式应用可以基于诸如数据发布/订阅、负载均衡、命名服务、分布式协调/通知，集群管理、Master选举、分布式锁和分布式队列。 </p>
</blockquote>
<a id="more"></a>
<h2 id="基本概念"><a href="#基本概念" class="headerlink" title="基本概念"></a>基本概念</h2><h2 id="zookeeper-应用场景"><a href="#zookeeper-应用场景" class="headerlink" title="zookeeper 应用场景"></a>zookeeper 应用场景</h2><h3 id="数据的发布、订阅"><a href="#数据的发布、订阅" class="headerlink" title="数据的发布、订阅"></a>数据的发布、订阅</h3><p>一方可以发布数据另一方接受数据</p>
<p>通常数据的订阅、发布 有两种方式：push / pull<br>zk 采用两种方式相结合</p>
<p>发布者将数据发布到集群的节点上，订阅者通过一定的方法告诉服务器，我对那个节点的数据感兴趣，那个服务器在这些节点的数据发生变化时，就通知客户端，客户端得到通知后就可以去服务端获取数据</p>
<h3 id="负载均衡"><a href="#负载均衡" class="headerlink" title="负载均衡"></a>负载均衡</h3><h3 id="DB"><a href="#DB" class="headerlink" title="DB"></a>DB</h3><ol>
<li>首先DB在启动的是先把自己在zk 注册成一个临时的节点，zk的节点有两种一种是永久节点，另一种是临时节点。临时节点在服务器出现问题的时候，节点会自动从zk上删除，那么这样zk上的服务器列表是最新的可用的列表</li>
<li>客户端需要读写数据库的时候首先去zk得到所有可用的DB连接信息（一张列表）</li>
<li>客户端随机选择一台进行连接</li>
<li>当客户端发现连接的时候再次从zk上获取可用的DB信息，当然也可以在刚获取的那个列表里移除掉不可用的连接后再选择一个DB连接</li>
</ol>
<h3 id="命名服务"><a href="#命名服务" class="headerlink" title="命名服务"></a>命名服务</h3><pre><code> 顾名思义就是提供名称服务，例如数据库表格ID，一般有两种ID，一种是分布式中使用的，一种是自增长的ID，UUID 可以在分布式中使用但由于没有规律较难理解，友好性不好，我们可以使用zk来生成一个顺序增长的，可以在集群环境下使用。
</code></pre><h3 id="分布式协调-通知"><a href="#分布式协调-通知" class="headerlink" title="分布式协调/通知"></a>分布式协调/通知</h3><p>心跳检测<br>在分布式系统中，我们常常需要知道某个服务器是否可用，传统开发中，可以通过ping 某个主机。zk 中我们让所有机器都注册到一个临时节点，我们判断一个机器是否可用，我们只需判断这个节点zk是否存在就可以了，不需要直接去连接需要检查的机器，降低系统的复杂度。</p>
<h2 id="环境搭建"><a href="#环境搭建" class="headerlink" title="环境搭建"></a>环境搭建</h2><ol>
<li><p>安装</p>
<p>  <code>wget http://mirrors.hust.edu.cn/apache/zookeeper/zookeeper-3.3.6/</code></p>
</li>
<li><p>解压</p>
<p>   <code>tar zxf zookeeper-3.3.6  &amp;&amp; mv zookeeper-3.3.6 /usr/local/zookeeper</code></p>
</li>
<li><p>配置</p>
<p>  <code>vi /usr/local/&lt;zookeeper&gt;/conf/zoo.cnf</code></p>
</li>
</ol>
<pre><code> ```

      server.1=host:port:port-leader 

      server.2=host:port:port-leader   

      server.3=host:port:port-leader 
      touch myid &amp;&amp; echo "&lt;id&gt;" &gt; myid
 ```
</code></pre><ol>
<li><p>启动/停止</p>
<p>  <code>./zkServer start | stop</code></p>
</li>
<li><p>客户端连接<br>  <code>./zkCli</code></p>
</li>
</ol>
<h2 id="master选举"><a href="#master选举" class="headerlink" title="master选举"></a>master选举</h2><p><strong>架构图</strong>:<br><img src="https://dn-imjun.qbox.me/2016-07-25-11-10-26.jpg" alt=""><br><strong>程序流程图:</strong></p>
<p><img src="https://dn-imjun.qbox.me/2016-07-25-11-11-03.jpg" alt=""><br><strong>网络抖动:</strong></p>
<p><img src="https://dn-imjun.qbox.me/2016-07-25-11-11-41.jpg" alt=""><br><strong>核心类图:</strong></p>
<p><img src="https://dn-imjun.qbox.me/2016-07-25-11-12-08.jpg" alt=""></p>
<p>master 节点何时会删除</p>
<ol>
<li><p>master 会主动放权</p>
</li>
<li><p>master 节点down机</p>
</li>
<li><p>master 节点网络斗动，会发生新一轮选举</p>
</li>
<li><p>如果master 和上一轮选举的master 不是同一个节点，不一致时发生资源迁移</p>
</li>
</ol>
<p>优化：让上一轮选举出的master 再新一轮选举中优先采用master 节点</p>
<p><strong>代码:</strong></p>
<pre class=" language-java"><code class="language-java"><span class="token keyword">package</span> com<span class="token punctuation">.</span>shaojun<span class="token punctuation">.</span>zookeeper<span class="token punctuation">.</span>mastersel<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>I0Itec<span class="token punctuation">.</span>zkclient<span class="token punctuation">.</span>ZkClient<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>I0Itec<span class="token punctuation">.</span>zkclient<span class="token punctuation">.</span>serialize<span class="token punctuation">.</span>SerializableSerializer<span class="token punctuation">;</span>

<span class="token keyword">import</span> java<span class="token punctuation">.</span>io<span class="token punctuation">.</span>BufferedReader<span class="token punctuation">;</span>
<span class="token keyword">import</span> java<span class="token punctuation">.</span>io<span class="token punctuation">.</span>InputStreamReader<span class="token punctuation">;</span>
<span class="token keyword">import</span> java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>ArrayList<span class="token punctuation">;</span>
<span class="token keyword">import</span> java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>List<span class="token punctuation">;</span>

<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">LeaderSelectorZkClient</span>
<span class="token punctuation">{</span>
    <span class="token comment" spellcheck="true">//启动的服务个数</span>
    <span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token keyword">final</span> <span class="token keyword">int</span>        CLIENT_QTY <span class="token operator">=</span> <span class="token number">10</span><span class="token punctuation">;</span>
    <span class="token comment" spellcheck="true">//zookeeper服务器的地址</span>
    <span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token keyword">final</span>  String  ZOOKEEPER_SERVER <span class="token operator">=</span> <span class="token string">"10.3.1.11:2181,10.3.1.11:2182,10.3.1.11:2183"</span><span class="token punctuation">;</span>


    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span>String<span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token keyword">throws</span> Exception
    <span class="token punctuation">{</span>
        <span class="token comment" spellcheck="true">//保存所有zkClient的列表</span>
        List<span class="token operator">&lt;</span>ZkClient<span class="token operator">></span>  clients <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ArrayList</span><span class="token operator">&lt;</span>ZkClient<span class="token operator">></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment" spellcheck="true">//保存所有服务的列表</span>
        List<span class="token operator">&lt;</span>WorkServer<span class="token operator">></span>  workServers <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ArrayList</span><span class="token operator">&lt;</span>WorkServer<span class="token operator">></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">try</span>
        <span class="token punctuation">{</span>
            <span class="token keyword">for</span> <span class="token punctuation">(</span> <span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> CLIENT_QTY<span class="token punctuation">;</span> <span class="token operator">++</span>i <span class="token punctuation">)</span>
            <span class="token punctuation">{</span>
                <span class="token comment" spellcheck="true">//创建zkClient</span>
                ZkClient client <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ZkClient</span><span class="token punctuation">(</span>ZOOKEEPER_SERVER<span class="token punctuation">,</span> <span class="token number">15000</span><span class="token punctuation">,</span> <span class="token number">105000</span><span class="token punctuation">,</span> <span class="token keyword">new</span> <span class="token class-name">SerializableSerializer</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                clients<span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span>client<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token comment" spellcheck="true">//创建serverData</span>
                RunningData runningData <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">RunningData</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                runningData<span class="token punctuation">.</span><span class="token function">setCid</span><span class="token punctuation">(</span>Long<span class="token punctuation">.</span><span class="token function">valueOf</span><span class="token punctuation">(</span>i<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                runningData<span class="token punctuation">.</span><span class="token function">setName</span><span class="token punctuation">(</span><span class="token string">"Client #"</span> <span class="token operator">+</span> i<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token comment" spellcheck="true">//创建服务</span>
                WorkServer  workServer <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">WorkServer</span><span class="token punctuation">(</span>runningData<span class="token punctuation">)</span><span class="token punctuation">;</span>
                workServer<span class="token punctuation">.</span><span class="token function">setZkClient</span><span class="token punctuation">(</span>client<span class="token punctuation">)</span><span class="token punctuation">;</span>

                workServers<span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span>workServer<span class="token punctuation">)</span><span class="token punctuation">;</span>
                workServer<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span>

            System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"敲回车键退出！\n"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">new</span> <span class="token class-name">BufferedReader</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">InputStreamReader</span><span class="token punctuation">(</span>System<span class="token punctuation">.</span>in<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">readLine</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
        <span class="token keyword">finally</span>
        <span class="token punctuation">{</span>
            System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"Shutting down..."</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

            <span class="token keyword">for</span> <span class="token punctuation">(</span> WorkServer workServer <span class="token operator">:</span> workServers <span class="token punctuation">)</span>
            <span class="token punctuation">{</span>
                <span class="token keyword">try</span> <span class="token punctuation">{</span>
                    workServer<span class="token punctuation">.</span><span class="token function">stop</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Exception</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
                    e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">}</span>               
            <span class="token punctuation">}</span>
            <span class="token keyword">for</span> <span class="token punctuation">(</span> ZkClient client <span class="token operator">:</span> clients <span class="token punctuation">)</span>
            <span class="token punctuation">{</span>
                <span class="token keyword">try</span> <span class="token punctuation">{</span>
                    client<span class="token punctuation">.</span><span class="token function">close</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Exception</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
                    e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">}</span>               
            <span class="token punctuation">}</span>
        <span class="token punctuation">}</span>        
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre>
<p><strong>running data 实体类</strong></p>
<pre class=" language-java"><code class="language-java"><span class="token keyword">package</span> com<span class="token punctuation">.</span>shaojun<span class="token punctuation">.</span>zookeeper<span class="token punctuation">.</span>mastersel<span class="token punctuation">;</span>

<span class="token keyword">import</span> java<span class="token punctuation">.</span>io<span class="token punctuation">.</span>Serializable<span class="token punctuation">;</span>

<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">RunningData</span> <span class="token keyword">implements</span> <span class="token class-name">Serializable</span> <span class="token punctuation">{</span>

    <span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token keyword">final</span> <span class="token keyword">long</span> serialVersionUID <span class="token operator">=</span> 4260577459043203630L<span class="token punctuation">;</span>

    <span class="token keyword">private</span> Long cid<span class="token punctuation">;</span>
    <span class="token keyword">private</span> String name<span class="token punctuation">;</span>
    <span class="token keyword">public</span> Long <span class="token function">getCid</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> cid<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">setCid</span><span class="token punctuation">(</span>Long cid<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>cid <span class="token operator">=</span> cid<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">public</span> String <span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> name<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">setName</span><span class="token punctuation">(</span>String name<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>name <span class="token operator">=</span> name<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre>
<p><strong>工作服务器类:</strong></p>
<pre class=" language-java"><code class="language-java"><span class="token keyword">package</span> com<span class="token punctuation">.</span>shaojun<span class="token punctuation">.</span>zookeeper<span class="token punctuation">.</span>mastersel<span class="token punctuation">;</span>

<span class="token keyword">import</span> org<span class="token punctuation">.</span>I0Itec<span class="token punctuation">.</span>zkclient<span class="token punctuation">.</span>IZkDataListener<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>I0Itec<span class="token punctuation">.</span>zkclient<span class="token punctuation">.</span>ZkClient<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>I0Itec<span class="token punctuation">.</span>zkclient<span class="token punctuation">.</span>exception<span class="token punctuation">.</span>ZkException<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>I0Itec<span class="token punctuation">.</span>zkclient<span class="token punctuation">.</span>exception<span class="token punctuation">.</span>ZkInterruptedException<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>I0Itec<span class="token punctuation">.</span>zkclient<span class="token punctuation">.</span>exception<span class="token punctuation">.</span>ZkNoNodeException<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>I0Itec<span class="token punctuation">.</span>zkclient<span class="token punctuation">.</span>exception<span class="token punctuation">.</span>ZkNodeExistsException<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>apache<span class="token punctuation">.</span>zookeeper<span class="token punctuation">.</span>CreateMode<span class="token punctuation">;</span>

<span class="token keyword">import</span> java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>Executors<span class="token punctuation">;</span>
<span class="token keyword">import</span> java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>ScheduledExecutorService<span class="token punctuation">;</span>
<span class="token keyword">import</span> java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>TimeUnit<span class="token punctuation">;</span>

<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">WorkServer</span> <span class="token punctuation">{</span>

    <span class="token keyword">private</span> <span class="token keyword">volatile</span> <span class="token keyword">boolean</span> running <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>

    <span class="token keyword">private</span> ZkClient zkClient<span class="token punctuation">;</span>

    <span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token keyword">final</span> String MASTER_PATH <span class="token operator">=</span> <span class="token string">"/master"</span><span class="token punctuation">;</span>

    <span class="token keyword">private</span> IZkDataListener dataListener<span class="token punctuation">;</span>

    <span class="token keyword">private</span> RunningData serverData<span class="token punctuation">;</span>

    <span class="token keyword">private</span> RunningData masterData<span class="token punctuation">;</span>

    <span class="token keyword">private</span> ScheduledExecutorService delayExector <span class="token operator">=</span> Executors<span class="token punctuation">.</span><span class="token function">newScheduledThreadPool</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">private</span> <span class="token keyword">int</span> delayTime <span class="token operator">=</span> <span class="token number">5</span><span class="token punctuation">;</span>

    <span class="token keyword">public</span> <span class="token function">WorkServer</span><span class="token punctuation">(</span>RunningData rd<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>serverData <span class="token operator">=</span> rd<span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>dataListener <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">IZkDataListener</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>

            <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">handleDataDeleted</span><span class="token punctuation">(</span>String dataPath<span class="token punctuation">)</span> <span class="token keyword">throws</span> Exception <span class="token punctuation">{</span>
                <span class="token comment" spellcheck="true">// TODO Auto-generated method stub</span>

                <span class="token comment" spellcheck="true">//takeMaster();</span>


                <span class="token keyword">if</span> <span class="token punctuation">(</span>masterData<span class="token operator">!=</span>null <span class="token operator">&amp;&amp;</span> masterData<span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>serverData<span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
                    <span class="token function">takeMaster</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

                <span class="token punctuation">}</span><span class="token keyword">else</span><span class="token punctuation">{</span>
                    delayExector<span class="token punctuation">.</span><span class="token function">schedule</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Runnable</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
                        <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
                            <span class="token function">takeMaster</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                        <span class="token punctuation">}</span>
                    <span class="token punctuation">}</span><span class="token punctuation">,</span> delayTime<span class="token punctuation">,</span> TimeUnit<span class="token punctuation">.</span>SECONDS<span class="token punctuation">)</span><span class="token punctuation">;</span>

                <span class="token punctuation">}</span>


            <span class="token punctuation">}</span>

            <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">handleDataChange</span><span class="token punctuation">(</span>String dataPath<span class="token punctuation">,</span> Object data<span class="token punctuation">)</span>
                    <span class="token keyword">throws</span> Exception <span class="token punctuation">{</span>
                <span class="token comment" spellcheck="true">// TODO Auto-generated method stub</span>

            <span class="token punctuation">}</span>
        <span class="token punctuation">}</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">public</span> ZkClient <span class="token function">getZkClient</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> zkClient<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">setZkClient</span><span class="token punctuation">(</span>ZkClient zkClient<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>zkClient <span class="token operator">=</span> zkClient<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> Exception <span class="token punctuation">{</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>running<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">Exception</span><span class="token punctuation">(</span><span class="token string">"server has startup..."</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
        running <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
        zkClient<span class="token punctuation">.</span><span class="token function">subscribeDataChanges</span><span class="token punctuation">(</span>MASTER_PATH<span class="token punctuation">,</span> dataListener<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token function">takeMaster</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token punctuation">}</span>

    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">stop</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> Exception <span class="token punctuation">{</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span>running<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">Exception</span><span class="token punctuation">(</span><span class="token string">"server has stoped"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
        running <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>

        delayExector<span class="token punctuation">.</span><span class="token function">shutdown</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        zkClient<span class="token punctuation">.</span><span class="token function">unsubscribeDataChanges</span><span class="token punctuation">(</span>MASTER_PATH<span class="token punctuation">,</span> dataListener<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token function">releaseMaster</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token punctuation">}</span>

    <span class="token keyword">private</span> <span class="token keyword">void</span> <span class="token function">takeMaster</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span>running<span class="token punctuation">)</span>
            <span class="token keyword">return</span><span class="token punctuation">;</span>

        <span class="token keyword">try</span> <span class="token punctuation">{</span>
            zkClient<span class="token punctuation">.</span><span class="token function">create</span><span class="token punctuation">(</span>MASTER_PATH<span class="token punctuation">,</span> serverData<span class="token punctuation">,</span> CreateMode<span class="token punctuation">.</span>EPHEMERAL<span class="token punctuation">)</span><span class="token punctuation">;</span>
            masterData <span class="token operator">=</span> serverData<span class="token punctuation">;</span>
            System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>serverData<span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">+</span><span class="token string">" is master"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            delayExector<span class="token punctuation">.</span><span class="token function">schedule</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Runnable</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>          
                <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                    <span class="token comment" spellcheck="true">// TODO Auto-generated method stub</span>
                    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token function">checkMaster</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
                        <span class="token function">releaseMaster</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">}</span>
                <span class="token punctuation">}</span>
            <span class="token punctuation">}</span><span class="token punctuation">,</span> <span class="token number">5</span><span class="token punctuation">,</span> TimeUnit<span class="token punctuation">.</span>SECONDS<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">ZkNodeExistsException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            RunningData runningData <span class="token operator">=</span> zkClient<span class="token punctuation">.</span><span class="token function">readData</span><span class="token punctuation">(</span>MASTER_PATH<span class="token punctuation">,</span> <span class="token boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>runningData <span class="token operator">==</span> null<span class="token punctuation">)</span> <span class="token punctuation">{</span>
                <span class="token function">takeMaster</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
                masterData <span class="token operator">=</span> runningData<span class="token punctuation">;</span>
            <span class="token punctuation">}</span>
        <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Exception</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token comment" spellcheck="true">// ignore;</span>
        <span class="token punctuation">}</span>

    <span class="token punctuation">}</span>

    <span class="token keyword">private</span> <span class="token keyword">void</span> <span class="token function">releaseMaster</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token function">checkMaster</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            zkClient<span class="token punctuation">.</span><span class="token function">delete</span><span class="token punctuation">(</span>MASTER_PATH<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token punctuation">}</span>

    <span class="token punctuation">}</span>

    <span class="token keyword">private</span> <span class="token keyword">boolean</span> <span class="token function">checkMaster</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">try</span> <span class="token punctuation">{</span>
            RunningData eventData <span class="token operator">=</span> zkClient<span class="token punctuation">.</span><span class="token function">readData</span><span class="token punctuation">(</span>MASTER_PATH<span class="token punctuation">)</span><span class="token punctuation">;</span>
            masterData <span class="token operator">=</span> eventData<span class="token punctuation">;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>masterData<span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>serverData<span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                <span class="token keyword">return</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span>
            <span class="token keyword">return</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">ZkNoNodeException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token keyword">return</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">ZkInterruptedException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token keyword">return</span> <span class="token function">checkMaster</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">ZkException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token keyword">return</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre>
<h2 id="发布-订阅"><a href="#发布-订阅" class="headerlink" title="发布/订阅"></a>发布/订阅</h2><p><strong>架构图:</strong><br><img src="https://dn-imjun.qbox.me/2016-07-25-11-17-16.jpg" alt=""><br><strong>Manga Server 流程图:</strong></p>
<p><img src="https://dn-imjun.qbox.me/2016-07-25-11-17-48.jpg" alt=""><br><strong>WorkServer 流程图:</strong></p>
<p><img src="https://dn-imjun.qbox.me/2016-07-25-11-18-27.jpg" alt=""><br><strong>系统核心类图:</strong></p>
<p><img src="https://dn-imjun.qbox.me/2016-07-25-11-19-14.jpg" alt=""><br><strong>代码:</strong></p>
<pre class=" language-java"><code class="language-java"><span class="token keyword">package</span> com<span class="token punctuation">.</span>shaojun<span class="token punctuation">.</span>zookeeper<span class="token punctuation">.</span>subscribe<span class="token punctuation">;</span>

<span class="token keyword">import</span> java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>List<span class="token punctuation">;</span>

<span class="token keyword">import</span> org<span class="token punctuation">.</span>I0Itec<span class="token punctuation">.</span>zkclient<span class="token punctuation">.</span>IZkChildListener<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>I0Itec<span class="token punctuation">.</span>zkclient<span class="token punctuation">.</span>IZkDataListener<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>I0Itec<span class="token punctuation">.</span>zkclient<span class="token punctuation">.</span>ZkClient<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>I0Itec<span class="token punctuation">.</span>zkclient<span class="token punctuation">.</span>exception<span class="token punctuation">.</span>ZkNoNodeException<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>I0Itec<span class="token punctuation">.</span>zkclient<span class="token punctuation">.</span>exception<span class="token punctuation">.</span>ZkNodeExistsException<span class="token punctuation">;</span>

<span class="token keyword">import</span> com<span class="token punctuation">.</span>alibaba<span class="token punctuation">.</span>fastjson<span class="token punctuation">.</span>JSON<span class="token punctuation">;</span>

<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">ManageServer</span> <span class="token punctuation">{</span>

    <span class="token keyword">private</span> String serversPath<span class="token punctuation">;</span>
    <span class="token keyword">private</span> String commandPath<span class="token punctuation">;</span>
    <span class="token keyword">private</span> String configPath<span class="token punctuation">;</span>
    <span class="token keyword">private</span> ZkClient zkClient<span class="token punctuation">;</span>
    <span class="token keyword">private</span> ServerConfig config<span class="token punctuation">;</span>
    <span class="token keyword">private</span> IZkChildListener childListener<span class="token punctuation">;</span>
    <span class="token keyword">private</span> IZkDataListener dataListener<span class="token punctuation">;</span>
    <span class="token keyword">private</span> List<span class="token operator">&lt;</span>String<span class="token operator">></span> workServerList<span class="token punctuation">;</span>

    <span class="token keyword">public</span> <span class="token function">ManageServer</span><span class="token punctuation">(</span>String serversPath<span class="token punctuation">,</span> String commandPath<span class="token punctuation">,</span>
            String configPath<span class="token punctuation">,</span> ZkClient zkClient<span class="token punctuation">,</span> ServerConfig config<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>serversPath <span class="token operator">=</span> serversPath<span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>commandPath <span class="token operator">=</span> commandPath<span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>zkClient <span class="token operator">=</span> zkClient<span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>config <span class="token operator">=</span> config<span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>configPath <span class="token operator">=</span> configPath<span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>childListener <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">IZkChildListener</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>

            <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">handleChildChange</span><span class="token punctuation">(</span>String parentPath<span class="token punctuation">,</span>
                    List<span class="token operator">&lt;</span>String<span class="token operator">></span> currentChilds<span class="token punctuation">)</span> <span class="token keyword">throws</span> Exception <span class="token punctuation">{</span>
                <span class="token comment" spellcheck="true">// TODO Auto-generated method stub</span>
                workServerList <span class="token operator">=</span> currentChilds<span class="token punctuation">;</span>

                System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"work server list changed, new list is "</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token function">execList</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

            <span class="token punctuation">}</span>
        <span class="token punctuation">}</span><span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>dataListener <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">IZkDataListener</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>

            <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">handleDataDeleted</span><span class="token punctuation">(</span>String dataPath<span class="token punctuation">)</span> <span class="token keyword">throws</span> Exception <span class="token punctuation">{</span>
                <span class="token comment" spellcheck="true">// TODO Auto-generated method stub</span>
                <span class="token comment" spellcheck="true">// ignore;</span>
            <span class="token punctuation">}</span>

            <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">handleDataChange</span><span class="token punctuation">(</span>String dataPath<span class="token punctuation">,</span> Object data<span class="token punctuation">)</span>
                    <span class="token keyword">throws</span> Exception <span class="token punctuation">{</span>
                <span class="token comment" spellcheck="true">// TODO Auto-generated method stub</span>
                String cmd <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">String</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token keyword">byte</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">)</span> data<span class="token punctuation">)</span><span class="token punctuation">;</span>
                System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"cmd:"</span><span class="token operator">+</span>cmd<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token function">exeCmd</span><span class="token punctuation">(</span>cmd<span class="token punctuation">)</span><span class="token punctuation">;</span>

            <span class="token punctuation">}</span>
        <span class="token punctuation">}</span><span class="token punctuation">;</span>

    <span class="token punctuation">}</span>

    <span class="token keyword">private</span> <span class="token keyword">void</span> <span class="token function">initRunning</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        zkClient<span class="token punctuation">.</span><span class="token function">subscribeDataChanges</span><span class="token punctuation">(</span>commandPath<span class="token punctuation">,</span> dataListener<span class="token punctuation">)</span><span class="token punctuation">;</span>
        zkClient<span class="token punctuation">.</span><span class="token function">subscribeChildChanges</span><span class="token punctuation">(</span>serversPath<span class="token punctuation">,</span> childListener<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token comment" spellcheck="true">/*
     * 1: list 2: create 3: modify
     */</span>
    <span class="token keyword">private</span> <span class="token keyword">void</span> <span class="token function">exeCmd</span><span class="token punctuation">(</span>String cmdType<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token string">"list"</span><span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>cmdType<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token function">execList</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token string">"create"</span><span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>cmdType<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token function">execCreate</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token string">"modify"</span><span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>cmdType<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token function">execModify</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>
            System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"error command!"</span> <span class="token operator">+</span> cmdType<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>

    <span class="token punctuation">}</span>

    <span class="token keyword">private</span> <span class="token keyword">void</span> <span class="token function">execList</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>workServerList<span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">private</span> <span class="token keyword">void</span> <span class="token function">execCreate</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span>zkClient<span class="token punctuation">.</span><span class="token function">exists</span><span class="token punctuation">(</span>configPath<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token keyword">try</span> <span class="token punctuation">{</span>
                zkClient<span class="token punctuation">.</span><span class="token function">createPersistent</span><span class="token punctuation">(</span>configPath<span class="token punctuation">,</span> JSON<span class="token punctuation">.</span><span class="token function">toJSONString</span><span class="token punctuation">(</span>config<span class="token punctuation">)</span>
                        <span class="token punctuation">.</span><span class="token function">getBytes</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">ZkNodeExistsException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
                zkClient<span class="token punctuation">.</span><span class="token function">writeData</span><span class="token punctuation">(</span>configPath<span class="token punctuation">,</span> JSON<span class="token punctuation">.</span><span class="token function">toJSONString</span><span class="token punctuation">(</span>config<span class="token punctuation">)</span>
                        <span class="token punctuation">.</span><span class="token function">getBytes</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">ZkNoNodeException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
                String parentDir <span class="token operator">=</span> configPath<span class="token punctuation">.</span><span class="token function">substring</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">,</span>
                        configPath<span class="token punctuation">.</span><span class="token function">lastIndexOf</span><span class="token punctuation">(</span><span class="token string">'/'</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                zkClient<span class="token punctuation">.</span><span class="token function">createPersistent</span><span class="token punctuation">(</span>parentDir<span class="token punctuation">,</span> <span class="token boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token function">execCreate</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">private</span> <span class="token keyword">void</span> <span class="token function">execModify</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        config<span class="token punctuation">.</span><span class="token function">setDbUser</span><span class="token punctuation">(</span>config<span class="token punctuation">.</span><span class="token function">getDbUser</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token string">"_modify"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">try</span> <span class="token punctuation">{</span>
            zkClient<span class="token punctuation">.</span><span class="token function">writeData</span><span class="token punctuation">(</span>configPath<span class="token punctuation">,</span> JSON<span class="token punctuation">.</span><span class="token function">toJSONString</span><span class="token punctuation">(</span>config<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getBytes</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">ZkNoNodeException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token function">execCreate</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token function">initRunning</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">stop</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        zkClient<span class="token punctuation">.</span><span class="token function">unsubscribeChildChanges</span><span class="token punctuation">(</span>serversPath<span class="token punctuation">,</span> childListener<span class="token punctuation">)</span><span class="token punctuation">;</span>
        zkClient<span class="token punctuation">.</span><span class="token function">unsubscribeDataChanges</span><span class="token punctuation">(</span>commandPath<span class="token punctuation">,</span> dataListener<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>
</code></pre>
<p><strong>Server Config:</strong></p>
<pre class=" language-java"><code class="language-java"><span class="token keyword">package</span> com<span class="token punctuation">.</span>shaojun<span class="token punctuation">.</span>zookeeper<span class="token punctuation">.</span>subscribe<span class="token punctuation">;</span>

<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">ServerConfig</span> <span class="token punctuation">{</span>

    <span class="token keyword">private</span> String dbUrl<span class="token punctuation">;</span>
    <span class="token keyword">private</span> String dbPwd<span class="token punctuation">;</span>
    <span class="token keyword">private</span> String dbUser<span class="token punctuation">;</span>
    <span class="token keyword">public</span> String <span class="token function">getDbUrl</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> dbUrl<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">setDbUrl</span><span class="token punctuation">(</span>String dbUrl<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>dbUrl <span class="token operator">=</span> dbUrl<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">public</span> String <span class="token function">getDbPwd</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> dbPwd<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">setDbPwd</span><span class="token punctuation">(</span>String dbPwd<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>dbPwd <span class="token operator">=</span> dbPwd<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">public</span> String <span class="token function">getDbUser</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> dbUser<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">setDbUser</span><span class="token punctuation">(</span>String dbUser<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>dbUser <span class="token operator">=</span> dbUser<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> String <span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token string">"ServerConfig [dbUrl="</span> <span class="token operator">+</span> dbUrl <span class="token operator">+</span> <span class="token string">", dbPwd="</span> <span class="token operator">+</span> dbPwd
                <span class="token operator">+</span> <span class="token string">", dbUser="</span> <span class="token operator">+</span> dbUser <span class="token operator">+</span> <span class="token string">"]"</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre>
<p><strong>Server data</strong></p>
<pre class=" language-java"><code class="language-java"><span class="token keyword">package</span> com<span class="token punctuation">.</span>shaojun<span class="token punctuation">.</span>zookeeper<span class="token punctuation">.</span>subscribe<span class="token punctuation">;</span>

<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">ServerData</span> <span class="token punctuation">{</span>

    <span class="token keyword">private</span> String address<span class="token punctuation">;</span>
    <span class="token keyword">private</span> Integer id<span class="token punctuation">;</span>
    <span class="token keyword">private</span> String name<span class="token punctuation">;</span>
    <span class="token keyword">public</span> String <span class="token function">getAddress</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> address<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">setAddress</span><span class="token punctuation">(</span>String address<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>address <span class="token operator">=</span> address<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">public</span> Integer <span class="token function">getId</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> id<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">setId</span><span class="token punctuation">(</span>Integer id<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>id <span class="token operator">=</span> id<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">public</span> String <span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> name<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">setName</span><span class="token punctuation">(</span>String name<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>name <span class="token operator">=</span> name<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> String <span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token string">"ServerData [address="</span> <span class="token operator">+</span> address <span class="token operator">+</span> <span class="token string">", id="</span> <span class="token operator">+</span> id <span class="token operator">+</span> <span class="token string">", name="</span>
                <span class="token operator">+</span> name <span class="token operator">+</span> <span class="token string">"]"</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre>
<p><strong>订阅发布入口:</strong></p>
<pre class=" language-java"><code class="language-java"><span class="token keyword">package</span> com<span class="token punctuation">.</span>shaojun<span class="token punctuation">.</span>zookeeper<span class="token punctuation">.</span>subscribe<span class="token punctuation">;</span>

<span class="token keyword">import</span> java<span class="token punctuation">.</span>io<span class="token punctuation">.</span>BufferedReader<span class="token punctuation">;</span>
<span class="token keyword">import</span> java<span class="token punctuation">.</span>io<span class="token punctuation">.</span>InputStreamReader<span class="token punctuation">;</span>
<span class="token keyword">import</span> java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>ArrayList<span class="token punctuation">;</span>
<span class="token keyword">import</span> java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>List<span class="token punctuation">;</span>

<span class="token keyword">import</span> org<span class="token punctuation">.</span>I0Itec<span class="token punctuation">.</span>zkclient<span class="token punctuation">.</span>ZkClient<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>I0Itec<span class="token punctuation">.</span>zkclient<span class="token punctuation">.</span>serialize<span class="token punctuation">.</span>BytesPushThroughSerializer<span class="token punctuation">;</span>


<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">SubscribeZkClient</span> <span class="token punctuation">{</span>

       <span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token keyword">final</span> <span class="token keyword">int</span>  CLIENT_QTY <span class="token operator">=</span> <span class="token number">5</span><span class="token punctuation">;</span>

        <span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token keyword">final</span> String  ZOOKEEPER_SERVER <span class="token operator">=</span> <span class="token string">"192.168.1.105:2181"</span><span class="token punctuation">;</span>

        <span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token keyword">final</span> String  CONFIG_PATH <span class="token operator">=</span> <span class="token string">"/config"</span><span class="token punctuation">;</span>
        <span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token keyword">final</span> String  COMMAND_PATH <span class="token operator">=</span> <span class="token string">"/command"</span><span class="token punctuation">;</span>
        <span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token keyword">final</span> String  SERVERS_PATH <span class="token operator">=</span> <span class="token string">"/servers"</span><span class="token punctuation">;</span>

        <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span>String<span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token keyword">throws</span> Exception
        <span class="token punctuation">{</span>

            List<span class="token operator">&lt;</span>ZkClient<span class="token operator">></span>  clients <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ArrayList</span><span class="token operator">&lt;</span>ZkClient<span class="token operator">></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            List<span class="token operator">&lt;</span>WorkServer<span class="token operator">></span>  workServers <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ArrayList</span><span class="token operator">&lt;</span>WorkServer<span class="token operator">></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            ManageServer manageServer <span class="token operator">=</span> null<span class="token punctuation">;</span>

            <span class="token keyword">try</span>
            <span class="token punctuation">{</span>
                ServerConfig initConfig <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ServerConfig</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                initConfig<span class="token punctuation">.</span><span class="token function">setDbPwd</span><span class="token punctuation">(</span><span class="token string">"123456"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                initConfig<span class="token punctuation">.</span><span class="token function">setDbUrl</span><span class="token punctuation">(</span><span class="token string">"jdbc:mysql://localhost:3306/mydb"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                initConfig<span class="token punctuation">.</span><span class="token function">setDbUser</span><span class="token punctuation">(</span><span class="token string">"root"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

                ZkClient clientManage <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ZkClient</span><span class="token punctuation">(</span>ZOOKEEPER_SERVER<span class="token punctuation">,</span> <span class="token number">5000</span><span class="token punctuation">,</span> <span class="token number">5000</span><span class="token punctuation">,</span> <span class="token keyword">new</span> <span class="token class-name">BytesPushThroughSerializer</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                manageServer <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ManageServer</span><span class="token punctuation">(</span>SERVERS_PATH<span class="token punctuation">,</span> COMMAND_PATH<span class="token punctuation">,</span>CONFIG_PATH<span class="token punctuation">,</span>clientManage<span class="token punctuation">,</span>initConfig<span class="token punctuation">)</span><span class="token punctuation">;</span>
                manageServer<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

                <span class="token keyword">for</span> <span class="token punctuation">(</span> <span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> CLIENT_QTY<span class="token punctuation">;</span> <span class="token operator">++</span>i <span class="token punctuation">)</span>
                <span class="token punctuation">{</span>
                    ZkClient client <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ZkClient</span><span class="token punctuation">(</span>ZOOKEEPER_SERVER<span class="token punctuation">,</span> <span class="token number">5000</span><span class="token punctuation">,</span> <span class="token number">5000</span><span class="token punctuation">,</span> <span class="token keyword">new</span> <span class="token class-name">BytesPushThroughSerializer</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    clients<span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span>client<span class="token punctuation">)</span><span class="token punctuation">;</span>
                    ServerData serverData <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ServerData</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    serverData<span class="token punctuation">.</span><span class="token function">setId</span><span class="token punctuation">(</span>i<span class="token punctuation">)</span><span class="token punctuation">;</span>
                    serverData<span class="token punctuation">.</span><span class="token function">setName</span><span class="token punctuation">(</span><span class="token string">"WorkServer#"</span><span class="token operator">+</span>i<span class="token punctuation">)</span><span class="token punctuation">;</span>
                    serverData<span class="token punctuation">.</span><span class="token function">setAddress</span><span class="token punctuation">(</span><span class="token string">"192.168.1."</span><span class="token operator">+</span>i<span class="token punctuation">)</span><span class="token punctuation">;</span>

                    WorkServer  workServer <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">WorkServer</span><span class="token punctuation">(</span>CONFIG_PATH<span class="token punctuation">,</span> SERVERS_PATH<span class="token punctuation">,</span> serverData<span class="token punctuation">,</span> client<span class="token punctuation">,</span> initConfig<span class="token punctuation">)</span><span class="token punctuation">;</span>
                    workServers<span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span>workServer<span class="token punctuation">)</span><span class="token punctuation">;</span>
                    workServer<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>                 

                <span class="token punctuation">}</span>               
                System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"敲回车键退出！\n"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">new</span> <span class="token class-name">BufferedReader</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">InputStreamReader</span><span class="token punctuation">(</span>System<span class="token punctuation">.</span>in<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">readLine</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

            <span class="token punctuation">}</span>
            <span class="token keyword">finally</span>
            <span class="token punctuation">{</span>
                System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"Shutting down..."</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

                <span class="token keyword">for</span> <span class="token punctuation">(</span> WorkServer workServer <span class="token operator">:</span> workServers <span class="token punctuation">)</span>
                <span class="token punctuation">{</span>
                    <span class="token keyword">try</span> <span class="token punctuation">{</span>
                        workServer<span class="token punctuation">.</span><span class="token function">stop</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Exception</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
                        e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">}</span>               
                <span class="token punctuation">}</span>
                <span class="token keyword">for</span> <span class="token punctuation">(</span> ZkClient client <span class="token operator">:</span> clients <span class="token punctuation">)</span>
                <span class="token punctuation">{</span>
                    <span class="token keyword">try</span> <span class="token punctuation">{</span>
                        client<span class="token punctuation">.</span><span class="token function">close</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Exception</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
                        e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">}</span>

                <span class="token punctuation">}</span>
            <span class="token punctuation">}</span>
        <span class="token punctuation">}</span>   
<span class="token punctuation">}</span>
</code></pre>
<p><strong>Work Server 类:</strong></p>
<pre class=" language-java"><code class="language-java"><span class="token keyword">package</span> com<span class="token punctuation">.</span>shaojun<span class="token punctuation">.</span>zookeeper<span class="token punctuation">.</span>subscribe<span class="token punctuation">;</span>

<span class="token keyword">import</span> org<span class="token punctuation">.</span>I0Itec<span class="token punctuation">.</span>zkclient<span class="token punctuation">.</span>IZkDataListener<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>I0Itec<span class="token punctuation">.</span>zkclient<span class="token punctuation">.</span>ZkClient<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>I0Itec<span class="token punctuation">.</span>zkclient<span class="token punctuation">.</span>exception<span class="token punctuation">.</span>ZkNoNodeException<span class="token punctuation">;</span>

<span class="token keyword">import</span> com<span class="token punctuation">.</span>alibaba<span class="token punctuation">.</span>fastjson<span class="token punctuation">.</span>JSON<span class="token punctuation">;</span>

<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">WorkServer</span> <span class="token punctuation">{</span>

    <span class="token keyword">private</span> ZkClient zkClient<span class="token punctuation">;</span>
    <span class="token keyword">private</span> String configPath<span class="token punctuation">;</span>
    <span class="token keyword">private</span> String serversPath<span class="token punctuation">;</span>
    <span class="token keyword">private</span> ServerData serverData<span class="token punctuation">;</span>
    <span class="token keyword">private</span> ServerConfig serverConfig<span class="token punctuation">;</span>
    <span class="token keyword">private</span> IZkDataListener dataListener<span class="token punctuation">;</span>

    <span class="token keyword">public</span> <span class="token function">WorkServer</span><span class="token punctuation">(</span>String configPath<span class="token punctuation">,</span> String serversPath<span class="token punctuation">,</span>
            ServerData serverData<span class="token punctuation">,</span> ZkClient zkClient<span class="token punctuation">,</span> ServerConfig initConfig<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>zkClient <span class="token operator">=</span> zkClient<span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>serversPath <span class="token operator">=</span> serversPath<span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>configPath <span class="token operator">=</span> configPath<span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>serverConfig <span class="token operator">=</span> initConfig<span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>serverData <span class="token operator">=</span> serverData<span class="token punctuation">;</span>

        <span class="token keyword">this</span><span class="token punctuation">.</span>dataListener <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">IZkDataListener</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>

            <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">handleDataDeleted</span><span class="token punctuation">(</span>String dataPath<span class="token punctuation">)</span> <span class="token keyword">throws</span> Exception <span class="token punctuation">{</span>
                <span class="token comment" spellcheck="true">// TODO Auto-generated method stub</span>

            <span class="token punctuation">}</span>

            <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">handleDataChange</span><span class="token punctuation">(</span>String dataPath<span class="token punctuation">,</span> Object data<span class="token punctuation">)</span>
                    <span class="token keyword">throws</span> Exception <span class="token punctuation">{</span>
                <span class="token comment" spellcheck="true">// TODO Auto-generated method stub</span>
                String retJson <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">String</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token keyword">byte</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">)</span>data<span class="token punctuation">)</span><span class="token punctuation">;</span>
                ServerConfig serverConfigLocal <span class="token operator">=</span> <span class="token punctuation">(</span>ServerConfig<span class="token punctuation">)</span>JSON<span class="token punctuation">.</span><span class="token function">parseObject</span><span class="token punctuation">(</span>retJson<span class="token punctuation">,</span>ServerConfig<span class="token punctuation">.</span><span class="token keyword">class</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token function">updateConfig</span><span class="token punctuation">(</span>serverConfigLocal<span class="token punctuation">)</span><span class="token punctuation">;</span>
                System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"new Work server config is:"</span><span class="token operator">+</span>serverConfig<span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

            <span class="token punctuation">}</span>
        <span class="token punctuation">}</span><span class="token punctuation">;</span>

    <span class="token punctuation">}</span>

    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"work server start..."</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token function">initRunning</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token punctuation">}</span>

    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">stop</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"work server stop..."</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        zkClient<span class="token punctuation">.</span><span class="token function">unsubscribeDataChanges</span><span class="token punctuation">(</span>configPath<span class="token punctuation">,</span> dataListener<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">private</span> <span class="token keyword">void</span> <span class="token function">initRunning</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>

        <span class="token function">registMe</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        zkClient<span class="token punctuation">.</span><span class="token function">subscribeDataChanges</span><span class="token punctuation">(</span>configPath<span class="token punctuation">,</span> dataListener<span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token punctuation">}</span>

    <span class="token keyword">private</span> <span class="token keyword">void</span> <span class="token function">registMe</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        String mePath <span class="token operator">=</span> serversPath<span class="token punctuation">.</span><span class="token function">concat</span><span class="token punctuation">(</span><span class="token string">"/"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">concat</span><span class="token punctuation">(</span>serverData<span class="token punctuation">.</span><span class="token function">getAddress</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">try</span> <span class="token punctuation">{</span>
            zkClient<span class="token punctuation">.</span><span class="token function">createEphemeral</span><span class="token punctuation">(</span>mePath<span class="token punctuation">,</span> JSON<span class="token punctuation">.</span><span class="token function">toJSONString</span><span class="token punctuation">(</span>serverData<span class="token punctuation">)</span>
                    <span class="token punctuation">.</span><span class="token function">getBytes</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">ZkNoNodeException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            zkClient<span class="token punctuation">.</span><span class="token function">createPersistent</span><span class="token punctuation">(</span>serversPath<span class="token punctuation">,</span> <span class="token boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token function">registMe</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">private</span> <span class="token keyword">void</span> <span class="token function">updateConfig</span><span class="token punctuation">(</span>ServerConfig serverConfig<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>serverConfig <span class="token operator">=</span> serverConfig<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre>
<h2 id="负载均衡-1"><a href="#负载均衡-1" class="headerlink" title="负载均衡"></a>负载均衡</h2><p><strong>架构图</strong></p>
<p><img src="https://dn-imjun.qbox.me/2016-07-25-11-24-14.jpg" alt=""><br><strong>客户端流程</strong></p>
<p><img src="https://dn-imjun.qbox.me/2016-07-25-11-24-37.jpg" alt=""><br><strong>服务端主体流程图</strong></p>
<p><img src="https://dn-imjun.qbox.me/2016-07-25-11-25-00.jpg" alt=""><br><strong>Server 核心类图</strong></p>
<p><img src="https://dn-imjun.qbox.me/2016-07-25-11-25-18.jpg" alt=""><br><strong>代码结构:</strong><br><strong>客户端</strong><br><img src="https://dn-imjun.qbox.me/2016-07-25-11-26-25.jpg" alt=""><br><strong>服务端</strong></p>
<p><img src="https://dn-imjun.qbox.me/2016-07-25-11-26-59.jpg" alt=""></p>
<h2 id="命名服务-1"><a href="#命名服务-1" class="headerlink" title="命名服务"></a>命名服务</h2><p><strong>架构图</strong><br><img src="https://dn-imjun.qbox.me/2016-07-25-11-30-32.jpg" alt=""><br><strong>核心算法</strong><br><img src="https://dn-imjun.qbox.me/2016-07-25-11-30-51.jpg" alt=""><br><strong>代码</strong></p>
<pre class=" language-java"><code class="language-java"><span class="token keyword">package</span> com<span class="token punctuation">.</span>shaojun<span class="token punctuation">.</span>zookeeper<span class="token punctuation">.</span>nameservice<span class="token punctuation">;</span>

<span class="token keyword">import</span> org<span class="token punctuation">.</span>I0Itec<span class="token punctuation">.</span>zkclient<span class="token punctuation">.</span>ZkClient<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>I0Itec<span class="token punctuation">.</span>zkclient<span class="token punctuation">.</span>exception<span class="token punctuation">.</span>ZkNodeExistsException<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>I0Itec<span class="token punctuation">.</span>zkclient<span class="token punctuation">.</span>serialize<span class="token punctuation">.</span>BytesPushThroughSerializer<span class="token punctuation">;</span>

<span class="token keyword">import</span> java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>ExecutorService<span class="token punctuation">;</span>
<span class="token keyword">import</span> java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>Executors<span class="token punctuation">;</span>
<span class="token keyword">import</span> java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>TimeUnit<span class="token punctuation">;</span>

<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">IdMaker</span> <span class="token punctuation">{</span>


    <span class="token keyword">private</span> ZkClient client <span class="token operator">=</span> null<span class="token punctuation">;</span>
    <span class="token keyword">private</span> <span class="token keyword">final</span> String server<span class="token punctuation">;</span>
    <span class="token keyword">private</span> <span class="token keyword">final</span> String root<span class="token punctuation">;</span>
    <span class="token keyword">private</span> <span class="token keyword">final</span> String nodeName<span class="token punctuation">;</span>
    <span class="token keyword">private</span> <span class="token keyword">volatile</span> <span class="token keyword">boolean</span> running <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
    <span class="token keyword">private</span> ExecutorService cleanExector <span class="token operator">=</span> null<span class="token punctuation">;</span>

    <span class="token keyword">public</span> <span class="token keyword">enum</span> RemoveMethod<span class="token punctuation">{</span>
        NONE<span class="token punctuation">,</span>IMMEDIATELY<span class="token punctuation">,</span>DELAY

    <span class="token punctuation">}</span>

    <span class="token keyword">public</span> <span class="token function">IdMaker</span><span class="token punctuation">(</span>String zkServer<span class="token punctuation">,</span>String root<span class="token punctuation">,</span>String nodeName<span class="token punctuation">)</span><span class="token punctuation">{</span>

        <span class="token keyword">this</span><span class="token punctuation">.</span>root <span class="token operator">=</span> root<span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>server <span class="token operator">=</span> zkServer<span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>nodeName <span class="token operator">=</span> nodeName<span class="token punctuation">;</span>

    <span class="token punctuation">}</span>

    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> Exception <span class="token punctuation">{</span>

        <span class="token keyword">if</span> <span class="token punctuation">(</span>running<span class="token punctuation">)</span>
            <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">Exception</span><span class="token punctuation">(</span><span class="token string">"server has stated..."</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        running <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>

        <span class="token function">init</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token punctuation">}</span>


    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">stop</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> Exception <span class="token punctuation">{</span>

        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span>running<span class="token punctuation">)</span>
            <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">Exception</span><span class="token punctuation">(</span><span class="token string">"server has stopped..."</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        running <span class="token operator">=</span> <span class="token boolean">false</span><span class="token punctuation">;</span>

        <span class="token function">freeResource</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token punctuation">}</span>


    <span class="token keyword">private</span> <span class="token keyword">void</span> <span class="token function">init</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>

        client <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ZkClient</span><span class="token punctuation">(</span>server<span class="token punctuation">,</span><span class="token number">5000</span><span class="token punctuation">,</span><span class="token number">5000</span><span class="token punctuation">,</span><span class="token keyword">new</span> <span class="token class-name">BytesPushThroughSerializer</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        cleanExector <span class="token operator">=</span> Executors<span class="token punctuation">.</span><span class="token function">newFixedThreadPool</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">try</span><span class="token punctuation">{</span>
            client<span class="token punctuation">.</span><span class="token function">createPersistent</span><span class="token punctuation">(</span>root<span class="token punctuation">,</span><span class="token boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span><span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">ZkNodeExistsException</span> e<span class="token punctuation">)</span><span class="token punctuation">{</span>
            <span class="token comment" spellcheck="true">//ignore;</span>
        <span class="token punctuation">}</span>

    <span class="token punctuation">}</span>

    <span class="token keyword">private</span> <span class="token keyword">void</span> <span class="token function">freeResource</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>

        cleanExector<span class="token punctuation">.</span><span class="token function">shutdown</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">try</span><span class="token punctuation">{</span>
            cleanExector<span class="token punctuation">.</span><span class="token function">awaitTermination</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">,</span> TimeUnit<span class="token punctuation">.</span>SECONDS<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token punctuation">}</span><span class="token keyword">catch</span><span class="token punctuation">(</span>InterruptedException e<span class="token punctuation">)</span><span class="token punctuation">{</span>
            e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span><span class="token keyword">finally</span><span class="token punctuation">{</span>
            cleanExector <span class="token operator">=</span> null<span class="token punctuation">;</span>
        <span class="token punctuation">}</span>

        <span class="token keyword">if</span> <span class="token punctuation">(</span>client<span class="token operator">!=</span>null<span class="token punctuation">)</span><span class="token punctuation">{</span>
            client<span class="token punctuation">.</span><span class="token function">close</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            client<span class="token operator">=</span>null<span class="token punctuation">;</span>

        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">private</span> <span class="token keyword">void</span> <span class="token function">checkRunning</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> Exception <span class="token punctuation">{</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span>running<span class="token punctuation">)</span>
            <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">Exception</span><span class="token punctuation">(</span><span class="token string">"请先调用start"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token punctuation">}</span>

    <span class="token keyword">private</span> String <span class="token function">ExtractId</span><span class="token punctuation">(</span>String str<span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token keyword">int</span> index <span class="token operator">=</span> str<span class="token punctuation">.</span><span class="token function">lastIndexOf</span><span class="token punctuation">(</span>nodeName<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>index <span class="token operator">>=</span> <span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
            index<span class="token operator">+=</span>nodeName<span class="token punctuation">.</span><span class="token function">length</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">return</span> index <span class="token operator">&lt;=</span> str<span class="token punctuation">.</span><span class="token function">length</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">?</span>str<span class="token punctuation">.</span><span class="token function">substring</span><span class="token punctuation">(</span>index<span class="token punctuation">)</span><span class="token operator">:</span><span class="token string">""</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
        <span class="token keyword">return</span> str<span class="token punctuation">;</span>

    <span class="token punctuation">}</span>

    <span class="token keyword">public</span> String <span class="token function">generateId</span><span class="token punctuation">(</span>RemoveMethod removeMethod<span class="token punctuation">)</span> <span class="token keyword">throws</span> Exception<span class="token punctuation">{</span>
        <span class="token function">checkRunning</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">final</span> String fullNodePath <span class="token operator">=</span> root<span class="token punctuation">.</span><span class="token function">concat</span><span class="token punctuation">(</span><span class="token string">"/"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">concat</span><span class="token punctuation">(</span>nodeName<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">final</span> String ourPath <span class="token operator">=</span> client<span class="token punctuation">.</span><span class="token function">createPersistentSequential</span><span class="token punctuation">(</span>fullNodePath<span class="token punctuation">,</span> null<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">if</span> <span class="token punctuation">(</span>removeMethod<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>RemoveMethod<span class="token punctuation">.</span>IMMEDIATELY<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
            client<span class="token punctuation">.</span><span class="token function">delete</span><span class="token punctuation">(</span>ourPath<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span><span class="token keyword">else</span> <span class="token keyword">if</span> <span class="token punctuation">(</span>removeMethod<span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>RemoveMethod<span class="token punctuation">.</span>DELAY<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
            cleanExector<span class="token punctuation">.</span><span class="token function">execute</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Runnable</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>

                <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                    <span class="token comment" spellcheck="true">// TODO Auto-generated method stub</span>
                    client<span class="token punctuation">.</span><span class="token function">delete</span><span class="token punctuation">(</span>ourPath<span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">}</span>
            <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token punctuation">}</span>
        <span class="token comment" spellcheck="true">//node-0000000000, node-0000000001</span>
        <span class="token keyword">return</span> <span class="token function">ExtractId</span><span class="token punctuation">(</span>ourPath<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre>
<p><strong>测试</strong></p>
<pre class=" language-java"><code class="language-java"><span class="token keyword">package</span> com<span class="token punctuation">.</span>shaojun<span class="token punctuation">.</span>zookeeper<span class="token punctuation">.</span>nameservice<span class="token punctuation">;</span>


<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">TestIdMaker</span> <span class="token punctuation">{</span>

    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span>String<span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token keyword">throws</span> Exception <span class="token punctuation">{</span>

        IdMaker idMaker <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">IdMaker</span><span class="token punctuation">(</span><span class="token string">"localhost:2181"</span><span class="token punctuation">,</span>
                <span class="token string">"/NameService/IdGen"</span><span class="token punctuation">,</span> <span class="token string">"ID"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        idMaker<span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">try</span> <span class="token punctuation">{</span>
            <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> <span class="token number">10</span><span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                String id <span class="token operator">=</span> idMaker<span class="token punctuation">.</span><span class="token function">generateId</span><span class="token punctuation">(</span>IdMaker<span class="token punctuation">.</span>RemoveMethod<span class="token punctuation">.</span>DELAY<span class="token punctuation">)</span><span class="token punctuation">;</span>
                System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>id<span class="token punctuation">)</span><span class="token punctuation">;</span>

            <span class="token punctuation">}</span>
        <span class="token punctuation">}</span> <span class="token keyword">finally</span> <span class="token punctuation">{</span>
            idMaker<span class="token punctuation">.</span><span class="token function">stop</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre>
<h2 id="分布式队列"><a href="#分布式队列" class="headerlink" title="分布式队列"></a>分布式队列</h2><p><strong>架构图</strong><br><img src="https://dn-imjun.qbox.me/2016-07-25-11-31-24.jpg" alt=""><br><strong>offer 核心算法</strong><br><img src="https://dn-imjun.qbox.me/2016-07-25-11-31-32.jpg" alt=""><br><strong>poll 核心算法</strong><br><img src="https://dn-imjun.qbox.me/2016-07-25-11-31-40.jpg" alt=""><br><strong>核心代码</strong><br><strong>简单的队列</strong></p>
<pre class=" language-java"><code class="language-java"><span class="token keyword">package</span> com<span class="token punctuation">.</span>shaojun<span class="token punctuation">.</span>zookeeper<span class="token punctuation">.</span>queue<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>I0Itec<span class="token punctuation">.</span>zkclient<span class="token punctuation">.</span>ExceptionUtil<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>I0Itec<span class="token punctuation">.</span>zkclient<span class="token punctuation">.</span>ZkClient<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>I0Itec<span class="token punctuation">.</span>zkclient<span class="token punctuation">.</span>exception<span class="token punctuation">.</span>ZkNoNodeException<span class="token punctuation">;</span>

<span class="token keyword">import</span> java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>Collections<span class="token punctuation">;</span>
<span class="token keyword">import</span> java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>Comparator<span class="token punctuation">;</span>
<span class="token keyword">import</span> java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>List<span class="token punctuation">;</span>

<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">DistributedSimpleQueue</span><span class="token operator">&lt;</span>T<span class="token operator">></span> <span class="token punctuation">{</span>

    <span class="token keyword">protected</span> <span class="token keyword">final</span> ZkClient zkClient<span class="token punctuation">;</span>
    <span class="token keyword">protected</span> <span class="token keyword">final</span> String root<span class="token punctuation">;</span>

    <span class="token keyword">protected</span> <span class="token keyword">static</span> <span class="token keyword">final</span> String Node_NAME <span class="token operator">=</span> <span class="token string">"n_"</span><span class="token punctuation">;</span>
    <span class="token keyword">public</span> <span class="token function">DistributedSimpleQueue</span><span class="token punctuation">(</span>ZkClient zkClient<span class="token punctuation">,</span> String root<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>zkClient <span class="token operator">=</span> zkClient<span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>root <span class="token operator">=</span> root<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">public</span> <span class="token keyword">int</span> <span class="token function">size</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> zkClient<span class="token punctuation">.</span><span class="token function">getChildren</span><span class="token punctuation">(</span>root<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">size</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">public</span> <span class="token keyword">boolean</span> <span class="token function">isEmpty</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">return</span> zkClient<span class="token punctuation">.</span><span class="token function">getChildren</span><span class="token punctuation">(</span>root<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">size</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token number">0</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token keyword">public</span> <span class="token keyword">boolean</span> <span class="token function">offer</span><span class="token punctuation">(</span>T element<span class="token punctuation">)</span> <span class="token keyword">throws</span> Exception<span class="token punctuation">{</span>

        String nodeFullPath <span class="token operator">=</span> root <span class="token punctuation">.</span><span class="token function">concat</span><span class="token punctuation">(</span> <span class="token string">"/"</span> <span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">concat</span><span class="token punctuation">(</span> Node_NAME <span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">try</span> <span class="token punctuation">{</span>
            zkClient<span class="token punctuation">.</span><span class="token function">createPersistentSequential</span><span class="token punctuation">(</span>nodeFullPath <span class="token punctuation">,</span> element<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span><span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">ZkNoNodeException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            zkClient<span class="token punctuation">.</span><span class="token function">createPersistent</span><span class="token punctuation">(</span>root<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token function">offer</span><span class="token punctuation">(</span>element<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Exception</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token keyword">throw</span> ExceptionUtil<span class="token punctuation">.</span><span class="token function">convertToRuntimeException</span><span class="token punctuation">(</span>e<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
        <span class="token keyword">return</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>


    <span class="token annotation punctuation">@SuppressWarnings</span><span class="token punctuation">(</span><span class="token string">"unchecked"</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> T <span class="token function">poll</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> Exception <span class="token punctuation">{</span>

        <span class="token keyword">try</span> <span class="token punctuation">{</span>

            List<span class="token operator">&lt;</span>String<span class="token operator">></span> list <span class="token operator">=</span> zkClient<span class="token punctuation">.</span><span class="token function">getChildren</span><span class="token punctuation">(</span>root<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>list<span class="token punctuation">.</span><span class="token function">size</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                <span class="token keyword">return</span> null<span class="token punctuation">;</span>
            <span class="token punctuation">}</span>
            Collections<span class="token punctuation">.</span><span class="token function">sort</span><span class="token punctuation">(</span>list<span class="token punctuation">,</span> <span class="token keyword">new</span> <span class="token class-name">Comparator</span><span class="token operator">&lt;</span>String<span class="token operator">></span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                <span class="token keyword">public</span> <span class="token keyword">int</span> <span class="token function">compare</span><span class="token punctuation">(</span>String lhs<span class="token punctuation">,</span> String rhs<span class="token punctuation">)</span> <span class="token punctuation">{</span>
                    <span class="token keyword">return</span> <span class="token function">getNodeNumber</span><span class="token punctuation">(</span>lhs<span class="token punctuation">,</span> Node_NAME<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">compareTo</span><span class="token punctuation">(</span><span class="token function">getNodeNumber</span><span class="token punctuation">(</span>rhs<span class="token punctuation">,</span> Node_NAME<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">}</span>
            <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

            <span class="token keyword">for</span> <span class="token punctuation">(</span> String nodeName <span class="token operator">:</span> list <span class="token punctuation">)</span><span class="token punctuation">{</span>

                String nodeFullPath <span class="token operator">=</span> root<span class="token punctuation">.</span><span class="token function">concat</span><span class="token punctuation">(</span><span class="token string">"/"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">concat</span><span class="token punctuation">(</span>nodeName<span class="token punctuation">)</span><span class="token punctuation">;</span>    
                <span class="token keyword">try</span> <span class="token punctuation">{</span>
                    T node <span class="token operator">=</span> <span class="token punctuation">(</span>T<span class="token punctuation">)</span> zkClient<span class="token punctuation">.</span><span class="token function">readData</span><span class="token punctuation">(</span>nodeFullPath<span class="token punctuation">)</span><span class="token punctuation">;</span>
                    zkClient<span class="token punctuation">.</span><span class="token function">delete</span><span class="token punctuation">(</span>nodeFullPath<span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token keyword">return</span> node<span class="token punctuation">;</span>
                <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">ZkNoNodeException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
                    <span class="token comment" spellcheck="true">// ignore</span>
                <span class="token punctuation">}</span>
            <span class="token punctuation">}</span>

            <span class="token keyword">return</span> null<span class="token punctuation">;</span>

        <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Exception</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token keyword">throw</span> ExceptionUtil<span class="token punctuation">.</span><span class="token function">convertToRuntimeException</span><span class="token punctuation">(</span>e<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>

    <span class="token punctuation">}</span>

    <span class="token keyword">private</span> String <span class="token function">getNodeNumber</span><span class="token punctuation">(</span>String str<span class="token punctuation">,</span> String nodeName<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">int</span> index <span class="token operator">=</span> str<span class="token punctuation">.</span><span class="token function">lastIndexOf</span><span class="token punctuation">(</span>nodeName<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>index <span class="token operator">>=</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            index <span class="token operator">+=</span> Node_NAME<span class="token punctuation">.</span><span class="token function">length</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">return</span> index <span class="token operator">&lt;=</span> str<span class="token punctuation">.</span><span class="token function">length</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">?</span> str<span class="token punctuation">.</span><span class="token function">substring</span><span class="token punctuation">(</span>index<span class="token punctuation">)</span> <span class="token operator">:</span> <span class="token string">""</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
        <span class="token keyword">return</span> str<span class="token punctuation">;</span>

    <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre>
<p><strong>扩展队列</strong></p>
<pre class=" language-java"><code class="language-java"><span class="token keyword">package</span> com<span class="token punctuation">.</span>shaojun<span class="token punctuation">.</span>zookeeper<span class="token punctuation">.</span>queue<span class="token punctuation">;</span>




<span class="token keyword">import</span> org<span class="token punctuation">.</span>I0Itec<span class="token punctuation">.</span>zkclient<span class="token punctuation">.</span>IZkChildListener<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>I0Itec<span class="token punctuation">.</span>zkclient<span class="token punctuation">.</span>ZkClient<span class="token punctuation">;</span>

<span class="token keyword">import</span> java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>List<span class="token punctuation">;</span>
<span class="token keyword">import</span> java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>CountDownLatch<span class="token punctuation">;</span>


<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">DistributedBlockingQueue</span><span class="token operator">&lt;</span>T<span class="token operator">></span> <span class="token keyword">extends</span> <span class="token class-name">DistributedSimpleQueue</span><span class="token operator">&lt;</span>T<span class="token operator">></span><span class="token punctuation">{</span>      


    <span class="token keyword">public</span> <span class="token function">DistributedBlockingQueue</span><span class="token punctuation">(</span>ZkClient zkClient<span class="token punctuation">,</span> String root<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">super</span><span class="token punctuation">(</span>zkClient<span class="token punctuation">,</span> root<span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token punctuation">}</span>


    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> T <span class="token function">poll</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> Exception <span class="token punctuation">{</span>

        <span class="token keyword">while</span> <span class="token punctuation">(</span><span class="token boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">{</span>

            <span class="token keyword">final</span> CountDownLatch    latch <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">CountDownLatch</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">final</span> IZkChildListener childListener <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">IZkChildListener</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>

                <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">handleChildChange</span><span class="token punctuation">(</span>String parentPath<span class="token punctuation">,</span> List<span class="token operator">&lt;</span>String<span class="token operator">></span> currentChilds<span class="token punctuation">)</span>
                        <span class="token keyword">throws</span> Exception <span class="token punctuation">{</span>
                    latch<span class="token punctuation">.</span><span class="token function">countDown</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

                <span class="token punctuation">}</span>
            <span class="token punctuation">}</span><span class="token punctuation">;</span>
            zkClient<span class="token punctuation">.</span><span class="token function">subscribeChildChanges</span><span class="token punctuation">(</span>root<span class="token punctuation">,</span> childListener<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">try</span><span class="token punctuation">{</span>
                T node <span class="token operator">=</span> <span class="token keyword">super</span><span class="token punctuation">.</span><span class="token function">poll</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token keyword">if</span> <span class="token punctuation">(</span> node <span class="token operator">!=</span> null <span class="token punctuation">)</span><span class="token punctuation">{</span>
                    <span class="token keyword">return</span> node<span class="token punctuation">;</span>
                <span class="token punctuation">}</span><span class="token keyword">else</span><span class="token punctuation">{</span>
                    latch<span class="token punctuation">.</span><span class="token function">await</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token punctuation">}</span>
            <span class="token punctuation">}</span><span class="token keyword">finally</span><span class="token punctuation">{</span>
                zkClient<span class="token punctuation">.</span><span class="token function">unsubscribeChildChanges</span><span class="token punctuation">(</span>root<span class="token punctuation">,</span> childListener<span class="token punctuation">)</span><span class="token punctuation">;</span>

            <span class="token punctuation">}</span>

        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre>
<p><strong>测试类</strong></p>
<pre class=" language-java"><code class="language-java"><span class="token keyword">package</span> com<span class="token punctuation">.</span>shaojun<span class="token punctuation">.</span>zookeeper<span class="token punctuation">.</span>queue<span class="token punctuation">;</span>

<span class="token keyword">import</span> org<span class="token punctuation">.</span>I0Itec<span class="token punctuation">.</span>zkclient<span class="token punctuation">.</span>ZkClient<span class="token punctuation">;</span>
<span class="token keyword">import</span> org<span class="token punctuation">.</span>I0Itec<span class="token punctuation">.</span>zkclient<span class="token punctuation">.</span>serialize<span class="token punctuation">.</span>SerializableSerializer<span class="token punctuation">;</span>

<span class="token keyword">import</span> java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>Executors<span class="token punctuation">;</span>
<span class="token keyword">import</span> java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>ScheduledExecutorService<span class="token punctuation">;</span>
<span class="token keyword">import</span> java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>TimeUnit<span class="token punctuation">;</span>

<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">TestDistributedBlockingQueue</span> <span class="token punctuation">{</span>

    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span>String<span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token punctuation">{</span>


        ScheduledExecutorService delayExector <span class="token operator">=</span> Executors<span class="token punctuation">.</span><span class="token function">newScheduledThreadPool</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">int</span> delayTime <span class="token operator">=</span> <span class="token number">5</span><span class="token punctuation">;</span>

        ZkClient zkClient <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ZkClient</span><span class="token punctuation">(</span><span class="token string">"localhost:2181"</span><span class="token punctuation">,</span> <span class="token number">5000</span><span class="token punctuation">,</span> <span class="token number">5000</span><span class="token punctuation">,</span> <span class="token keyword">new</span> <span class="token class-name">SerializableSerializer</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">final</span> DistributedBlockingQueue<span class="token operator">&lt;</span>User<span class="token operator">></span> queue <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">DistributedBlockingQueue</span><span class="token operator">&lt;</span>User<span class="token operator">></span><span class="token punctuation">(</span>zkClient<span class="token punctuation">,</span><span class="token string">"/Queue"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">final</span> User user1 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">User</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        user1<span class="token punctuation">.</span><span class="token function">setId</span><span class="token punctuation">(</span><span class="token string">"1"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        user1<span class="token punctuation">.</span><span class="token function">setName</span><span class="token punctuation">(</span><span class="token string">"xiao wang"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token keyword">final</span> User user2 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">User</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        user2<span class="token punctuation">.</span><span class="token function">setId</span><span class="token punctuation">(</span><span class="token string">"2"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        user2<span class="token punctuation">.</span><span class="token function">setName</span><span class="token punctuation">(</span><span class="token string">"xiao wang"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>     

        <span class="token keyword">try</span> <span class="token punctuation">{</span>

            delayExector<span class="token punctuation">.</span><span class="token function">schedule</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Runnable</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>

                <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
                    <span class="token keyword">try</span> <span class="token punctuation">{</span>
                        queue<span class="token punctuation">.</span><span class="token function">offer</span><span class="token punctuation">(</span>user1<span class="token punctuation">)</span><span class="token punctuation">;</span>
                        queue<span class="token punctuation">.</span><span class="token function">offer</span><span class="token punctuation">(</span>user2<span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Exception</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
                        e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                    <span class="token punctuation">}</span>

                <span class="token punctuation">}</span>
            <span class="token punctuation">}</span><span class="token punctuation">,</span> delayTime <span class="token punctuation">,</span> TimeUnit<span class="token punctuation">.</span>SECONDS<span class="token punctuation">)</span><span class="token punctuation">;</span>

            System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"ready poll!"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            User u1 <span class="token operator">=</span> <span class="token punctuation">(</span>User<span class="token punctuation">)</span> queue<span class="token punctuation">.</span><span class="token function">poll</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            User u2 <span class="token operator">=</span> <span class="token punctuation">(</span>User<span class="token punctuation">)</span> queue<span class="token punctuation">.</span><span class="token function">poll</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

            <span class="token keyword">if</span> <span class="token punctuation">(</span>user1<span class="token punctuation">.</span><span class="token function">getId</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>u1<span class="token punctuation">.</span><span class="token function">getId</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token operator">&amp;&amp;</span> user2<span class="token punctuation">.</span><span class="token function">getId</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">equals</span><span class="token punctuation">(</span>u2<span class="token punctuation">.</span><span class="token function">getId</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
                System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"Success!"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span>

        <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Exception</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span> <span class="token keyword">finally</span><span class="token punctuation">{</span>
            delayExector<span class="token punctuation">.</span><span class="token function">shutdown</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">try</span> <span class="token punctuation">{</span>
                delayExector<span class="token punctuation">.</span><span class="token function">awaitTermination</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">,</span> TimeUnit<span class="token punctuation">.</span>SECONDS<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">InterruptedException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token punctuation">}</span>

        <span class="token punctuation">}</span>

    <span class="token punctuation">}</span>

<span class="token punctuation">}</span>
</code></pre>
<h2 id="分布式锁"><a href="#分布式锁" class="headerlink" title="分布式锁"></a>分布式锁</h2><p><strong>架构图</strong></p>
<p><img src="https://dn-imjun.qbox.me/2016-07-25-11-32-54.jpg" alt=""><br><strong>核心算法流程图</strong></p>
<p><img src="https://dn-imjun.qbox.me/2016-07-25-11-33-12.jpg" alt=""><br><strong>全局事务锁的相关代码</strong></p>
<p><img src="https://dn-imjun.qbox.me/2016-07-25-11-41-10.jpg" alt=""></p>
<script>
        document.querySelectorAll('.github-emoji')
          .forEach(el => {
            if (!el.dataset.src) { return; }
            const img = document.createElement('img');
            img.style = 'display:none !important;';
            img.src = el.dataset.src;
            img.addEventListener('error', () => {
              img.remove();
              el.style.color = 'inherit';
              el.style.backgroundImage = 'none';
              el.style.background = 'none';
            });
            img.addEventListener('load', () => {
              img.remove();
            });
            document.body.appendChild(img);
          });
      </script>
            </div>
            <hr/>

            
            <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.88rem;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-large waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fa fa-close"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>
            

            <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">

<div id="article-share">
    
    <div class="social-share" data-disabled="qzone" data-wechat-qrcode-helper="<p>微信里点“发现”->“扫一扫”二维码便可查看分享。</p>"></div>
    
</div>

<script src="/libs/share/js/social-share.min.js"></script>

            

    <div class="reprint" id="reprint-statement">
        <p class="reprint-tip">
            <i class="fa fa-exclamation-triangle"></i>&nbsp;&nbsp;
            <span>转载规则</span>
        </p>
        
            <div class="center-align">
                <a rel="license" href="https://creativecommons.org/licenses/by/4.0/deed.zh">
                    <img alt=""
                         style="border-width:0"
                         src="https://i.creativecommons.org/l/by/4.0/88x31.png"/>
                </a>
            </div>
            <br/>
            <span xmlns:dct="http://purl.org/dc/terms/" href="http://purl.org/dc/dcmitype/Text"
                  property="dct:title" rel="dct:type">
                    《zookeeper教程》
                </span> 由
            <a xmlns:cc="http://creativecommons.org/ns#" href="/2016/07/27/zookeeper-jiao-cheng/" property="cc:attributionName"
               rel="cc:attributionURL">
                码匠先生
            </a> 采用
            <a rel="license" href="https://creativecommons.org/licenses/by/4.0/deed.zh">
                知识共享署名 4.0 国际许可协议
            </a>进行许可。
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>


        </div>
    </div>

    
        <link rel="stylesheet" href="/libs/gitalk/gitalk.css">
<link rel="stylesheet" href="/css/my-gitalk.css">

<div class="card gitalk-card" data-aos="fade-up">
    <div id="gitalk-container" class="card-content"></div>
</div>

<script src="/libs/gitalk/gitalk.min.js"></script>
<script>
    let gitalk = new Gitalk({
        clientID: 'fd76f3072f4810ef950b',
        clientSecret: '8a2b52c03a622513675f6376cd8f0fbf78e590bc',
        repo: 'liushaojun.github.io',
        owner: 'liushaojun',
        admin: "liushaojun",
        id: '2016-07-27T10-07-53',
        distractionFreeMode: false  // Facebook-like distraction free mode
    });

    gitalk.render('gitalk-container');
</script>
    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fa fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2016/11/23/ios-zhua-bao-gong-ju/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/15.jpg" class="responsive-img" alt="IOS抓包工具">
                        
                        <span class="card-title">IOS抓包工具</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
在iOS开发过程中，抓包是常见的必备技能之一。这里我们主要介绍一下Mac下的抓包利器Charles（文中版本：4.0.1）。它可以非常方便的抓取Http/Https请求，从而提高我们的开发效率。本文中不提供破解版安装使用说明（网上一大堆）
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="fa fa-clock-o fa-fw icon-date"></i>2016-11-23
                        </span>
                        <span class="publish-author">
                            
                            <i class="fa fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/工具/" class="post-category" target="_blank">
                                    工具
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/https/" target="_blank">
                        <span class="chip bg-color">https</span>
                    </a>
                    
                    <a href="/tags/ios/" target="_blank">
                        <span class="chip bg-color">ios</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fa fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2016/05/09/zai-xian-gong-ju-lie-biao/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/6.jpg" class="responsive-img" alt="在线工具列表">
                        
                        <span class="card-title">在线工具列表</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
程序员的工具箱。

Java源代码搜索
Grepcode是一个面向于Java开发人员的网站，在这里你可以通过Java的projects、classes等各种关键字在线查看它对应的源码，知道对应的project、classes等信息。 更方
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="fa fa-clock-o fa-fw icon-date"></i>2016-05-09
                            </span>
                        <span class="publish-author">
                            
                            <i class="fa fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/工具/" class="post-category" target="_blank">
                                    工具
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/java/" target="_blank">
                        <span class="chip bg-color">java</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>
</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('120')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'PRE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + '来源: 码匠先生<br />'
            + '作者: 码匠先生<br />'
            + '链接: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {bodyElement.removeChild(newdiv);}, 200);
    });
</script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget">
            <div class="toc-title"><i class="fa fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fa fa-list"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            // headingsOffset: -205,
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).slideUp(500);
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).slideDown(500);
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>
    

</main>


<footer class="page-footer bg-color">
    <div class="container row center-align">
        <div class="col s12 m8 l8 copy-right">
            本站由&copy;<a href="https://blinkfox.github.io/" target="_blank">Blinkfox</a>基于
            <a href="https://hexo.io/" target="_blank">Hexo</a> 的
            <a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">hexo-theme-matery</a>主题搭建.

            
                &nbsp;<i class="fa fa-area-chart"></i>&nbsp;站点总字数:&nbsp;
                <span class="white-color">8.6k</span>
            

            
			
                <br>
                
                <span id="busuanzi_container_site_pv">
                    <i class="fa fa-heart-o"></i>
                    本站总访问量 <span id="busuanzi_value_site_pv" class="white-color"></span>
                </span>
                
                
                <span id="busuanzi_container_site_uv">
                    <i class="fa fa-users"></i>
                    次,&nbsp;访客数 <span id="busuanzi_value_site_uv" class="white-color"></span> 人.
                </span>
                
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/liushaojun" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fa fa-github"></i>
    </a>



    <a href="mailto:liushaojunvip@sina.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fa fa-envelope-open"></i>
    </a>





    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fa fa-rss"></i>
    </a>
</div>
    </div>
</footer>

<div class="progress-bar"></div>


<!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fa fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc("/" + "search.xml", 'searchInput', 'searchResult');
});
</script>
<!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fa fa-angle-up"></i>
    </a>
</div>


<script src="/libs/materialize/materialize.min.js"></script>
<script src="/libs/masonry/masonry.pkgd.min.js"></script>
<script src="/libs/aos/aos.js"></script>
<script src="/libs/scrollprogress/scrollProgress.min.js"></script>
<script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
<script src="/js/matery.js"></script>

<!-- Global site tag (gtag.js) - Google Analytics -->



    <script src="/libs/others/clicklove.js"></script>


    <script async src="/libs/others/busuanzi.pure.mini.js"></script>


</body>
</html>